<template>
	<view>
		<zmm-watermark :watermark="userStore.watermark" v-if="userStore.watermark"></zmm-watermark>
		<view class="content detail">
			<!--到店试品-->
			<view class="detail-item">
				<uni-section title="到店试品" type="line"></uni-section>
				<view class="detail-content formRef">
					<uni-forms ref="formRef" :model="formData" :rules="formRules" labelWidth="100px">
					  <uni-forms-item label="试品商品" name="productId" required>
					    <ty-data-select
					    	v-model="formData.productId"
					    	placeholder="请选择试品商品"
					  		dataKey="name"
					  		dataValue="id"
					  		filterable
					    	:localdata="tableList">
					  	</ty-data-select>
					  </uni-forms-item>
						<uni-forms-item label="试品用户姓名" name="followUserName" required>
					    <uni-easyinput v-model="formData.followUserName" placeholder="请输入试品用户姓名" />
					  </uni-forms-item>
						<uni-forms-item label="试品内容" name="content" required>
						  <uni-easyinput type="textarea" v-model="formData.content" placeholder="请输入试品内容" />
						</uni-forms-item>
						<uni-forms-item label="试品图片" name="image">
							<up-upload
								:fileList="fileList"
								@afterRead="afterRead"
								@delete="deletePic"
								name="image"
								multiple
								:maxCount="4"
								></up-upload>
						  <uni-easyinput style="display: none;" v-model="formData.image" placeholder="请输入门店照片" />
						</uni-forms-item>
					</uni-forms>
					<button type="primary" :disabled="isSubmit" :loading="isSubmit" @click="submit">提交</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app';
import { computed, onMounted, ref } from 'vue';
import { tab, auth, modal } from "@/plugins"
import { getTitle } from "@/utils/getter"
import { checkPermi, checkRole, checkOnlyPermi, checkOnlyRole } from "@/utils/permission"
import useUserStore from '@/store/modules/user'
import {
	salesmanClueFollowAdd,
	salesmanClueFollowDetail,
	salesmanClueFollowProduct,
	salesmanClueFollowProductTest } from "@/api/erp_api/sale"
import { upload } from "@/api/system/common"
import { addUserLocation } from '@/utils/ty.js';
import { salesmanClueFollowLevelList, salesmanClueFollowStatusList } from '@/utils/config.js'

	const userStore = useUserStore()
	const id = ref('')
	const clueId = ref('')
	const pointId = ref('')
	onLoad(async (option) => {
		if (option.clueId) {
			clueId.value = option.clueId
		}
		getList()
		if (option.id) {
			id.value = option.id
			formData.value.followUserName = userStore.user && userStore.user.nickName ? userStore.user.nickName : ''
			addUserLocation(userStore.user.userId).then(res => {
				// console.log(res)
				pointId.value = res.data.id
			})
			getDetail()
		}
	})
	
	// 获取详情
	const info = ref({})
	const isLoading = ref(false)
	const getDetail = () => {
		const params = {
			id: id.value
		}
		isLoading.value = true
		uni.showLoading({
			title: '数据加载中...'
		})
		salesmanClueFollowDetail(params).then(res => {
			info.value = res.data || {}
			isLoading.value = false
			uni.hideLoading()
	  }).catch(() => {
			isLoading.value = false
			uni.hideLoading()
		})
	}
	
	// 图片上传
	const fileList = ref([])
	
	// 删除图片
	const deletePic = (event) => {
	  fileList.value.splice(event.index, 1)
		formData.value.image = fileList.value.map(item => item.url).join(',')
	}
	
	// 新增图片
	const afterRead = async (event) => {
	  // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
	  let lists = [].concat(event.file)
	  let fileListLen = fileList.value.length
	  lists.map((item) => {
	    fileList.value.push({
	      ...item,
	      status: 'uploading',
	      message: '上传中',
	    });
	  });
	  for (let i = 0; i < lists.length; i++) {
	    const result = await upload(lists[i].url)
			const data = JSON.parse(result.data)
	    let item = fileList.value[fileListLen]
	    fileList.value.splice(fileListLen, 1, {
	      ...item,
	      status: 'success',
	      message: '',
	      url: data.url,
	    });
	    fileListLen++;
	  }
		formData.value.image = fileList.value.map(item => item.url).join(',')
	};
	
	// form表单数据
	const formData = ref({
		productId: '',
		followUserName: '',
		content: '',
		image: ''
	})
	const formRef = ref(null)
	const formRules = ref({
		productId: {
			rules: [{ required: true, errorMessage: '请选择试品商品' }]
		},
		followUserName: {
			rules: [{ required: true, errorMessage: '请输入试品用户姓名' }]
		},
		content: {
			rules: [{ required: true, errorMessage: '请输入试品内容' }]
		}
	})
	const isSubmit = ref(false)
	// 提交
	const submit = () => {
		formRef.value.validate().then(async formRes => {
			const params = { ...formRes }
			params.clueId = clueId.value
			params.followUserId = userStore.user.userId
			params.oldLevel = info.value.oldLevel ? info.value.oldLevel : ''
			params.newLevel = info.value.newLevel ? info.value.newLevel : ''
			params.followType = 3
			if (pointId.value) {
				params.pointId = pointId.value
			} else {
				uni.showModal({
					title: '提示',
					content: '位置获取失败请返回上级重试',
					success: function (res) {
						if (res.confirm) {
							uni.navigateBack({
								delta: 1
							})
						}
					}
				})
				return false
			}
			isSubmit.value = true
			// console.log(params)
			const salesmanClueFollowRes =  await salesmanClueFollowAdd(params)
			// console.log(salesmanClueFollowRes)
			if (salesmanClueFollowRes.data) {
				console.log(salesmanClueFollowRes.data)
				salesmanClueFollowProductTest({
					clueFollowProductId: formRes.productId,
					clueFollowId: salesmanClueFollowRes.data.id
				}).then(async (res) => {
					modal.showToast(res.msg)
					await uni.$u.sleep(1000)
					isSubmit.value = false
					clear()
					if (id.value) {
						uni.$emit('refreshList');  // 触发刷新事件
					}
					uni.navigateBack({
						delta: 1
					})
				}).catch(err => {
					isSubmit.value = false
				})
			} else {
				modal.showToast('试品失败')
			}
		})
	}
	// 清空
	const clear = () => {
		formData.value = {
			followUserName: '',
			content: '',
			productId: '',
			image: ''
		}
	}
	
	// 获取试品列表
	const tableList = ref([])
	const getList = () => {
		const params = {
			pageNum: 1,
			pageSize: 100
		}
		if (clueId.value) {
			params.clueId = clueId.value
		}
		// 销售
		// if (checkOnlyRole(['sales_man'])) {
		// 	params.applyId = userStore.user.userId
		// }
		salesmanClueFollowProduct(params).then(res => {
			tableList.value = res.rows.map(item => {
				return {
					...item,
					name: `${item.productName}-申请【${item.testNumber}】`
				}
			}) || []
	  }).catch(() => {
		})
	}
	
</script>

<style scoped lang="scss">
	
</style>
